/*
 * @Author: 抱著羊啃 1437670973@qq.com
 * @Date: 2025-04-25 21:51:19
 * @LastEditors: 抱著羊啃 1437670973@qq.com
 * @LastEditTime: 2025-05-15 15:30:10
 * @FilePath: \demo1\src\main\java\org\example\demo1\servlets\ManagePage\UpdateUserServlet.java
 * @Description: 這是預設設定,請設定`customMade`, 打開koroFileHeader查看配置 進行設定: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package org.example.demo1.servlets.ManagePage;

import com.google.gson.Gson;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
import java.io.File;  // 新增File类导入
import org.apache.ibatis.session.SqlSession;
import org.example.demo1.DAO.UserDao;
import org.example.demo1.utils.MybatisUtils;
import org.example.demo1.utils.FileUploadOss;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@WebServlet("/API/user/update")
@MultipartConfig  // 启用文件上传支持
public class UpdateUserServlet extends HttpServlet {
    private static final String TEMP_DIR = "D:\\tools\\web\\demo1\\src\\main\\webapp\\temp";
    // 创建线程池用于异步上传文件
    private static final ExecutorService executorService = Executors.newFixedThreadPool(5);

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 记录方法开始时间
        long methodStartTime = System.currentTimeMillis();
        
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        Map<String, Object> result = new HashMap<>();
        SqlSession sqlSession = null;

        try {
            // 获取普通参数
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String email = req.getParameter("email");
            String phone = req.getParameter("phone");
            String status = req.getParameter("status");

            // 处理文件上传
            Part avatarPart = req.getPart("avatar");  // 获取名为"avatar"的文件部分
            String avatarUrl = null;
            final String tempFilePath;
            
            if (avatarPart != null && avatarPart.getSize() > 0) {
                // 使用UUID生成唯一文件名
                String originalFileName = getFileName(avatarPart);
                String fileExtension = "";
                if (originalFileName.contains(".")) {
                    fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
                }
                final String fileName = UUID.randomUUID().toString() + fileExtension;
                
                // 确保临时目录存在
                File tempDir = new File(TEMP_DIR);
                if (!tempDir.exists()) {
                    tempDir.mkdirs();
                }
                
                // 临时保存文件
                tempFilePath = TEMP_DIR + "\\" + fileName;
                avatarPart.write(tempFilePath);
                
                // 设置默认头像URL，后续异步更新
                avatarUrl = "https://mysteriouslamb.oss-cn-hangzhou.aliyuncs.com/" + fileName;
                
                // 异步上传文件到OSS
                final String finalFileName = fileName;
                executorService.submit(() -> {
                    try {
                        long startTime = System.currentTimeMillis();
                        
                        // 使用FileUploadOss工具类上传到阿里云OSS
                        FileUploadOss.fileupload(finalFileName, tempFilePath);
                        
                        long endTime = System.currentTimeMillis();
                        long duration = endTime - startTime;
                        
                        System.out.println("异步上传文件 " + finalFileName + " 到OSS耗时: " + duration + "毫秒");
                        
                        // 上传成功后删除临时文件
                        File tempFile = new File(tempFilePath);
                        if (tempFile.exists()) {
                            tempFile.delete();
                        }
                    } catch (Exception e) {
                        System.err.println("异步上传文件到OSS失败: " + e.getMessage());
                        e.printStackTrace();
                    }
                });
                
                System.out.println("已启动异步上传任务，请求处理继续进行...");
            }

            // 构建更新参数
            Map<String, Object> params = new HashMap<>();
            params.put("username", username);
            if (password != null && !password.isEmpty()) {
                params.put("password", password);
            }
            if (email != null) {
                params.put("email", email);
            }
            if (phone != null) {
                params.put("phone", phone);
            }
            if (status != null && !status.isEmpty()) {
                params.put("status", Integer.parseInt(status));
            }
            if (avatarUrl != null) {
                params.put("avatar_url", avatarUrl);  // 假设数据库有avatar_url字段
            }

            sqlSession = MybatisUtils.getSqlSession();
            UserDao userDao = sqlSession.getMapper(UserDao.class);

            int updateCount = userDao.updateUserInformationManage(params);
            sqlSession.commit();

            if (updateCount > 0) {
                result.put("code", 200);
                result.put("msg", "用户信息更新成功，头像正在后台上传中");
            } else {
                result.put("code", 404);
                result.put("msg", "未找到对应用户或未做任何更改");
            }
        } catch (Exception e) {
            if (sqlSession != null) sqlSession.rollback();
            result.put("code", 500);
            result.put("msg", "系统错误: " + e.getMessage());
            e.printStackTrace();
        } finally {
            if (sqlSession != null) sqlSession.close();
        }

        // 记录方法结束时间并计算总耗时
        long methodEndTime = System.currentTimeMillis();
        long totalDuration = methodEndTime - methodStartTime;
        System.out.println("doPost方法总执行时间: " + totalDuration + "毫秒");

        out.print(new Gson().toJson(result));
        out.flush();
        out.close();
    }

    // 辅助方法：从Part中获取文件名
    private String getFileName(Part part) {
        String contentDisposition = part.getHeader("content-disposition");
        for (String cd : contentDisposition.split(";")) {
            if (cd.trim().startsWith("filename")) {
                return cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return "default.jpg";
    }
    
    @Override
    public void destroy() {
        // 在Servlet销毁时关闭线程池
        executorService.shutdown();
        super.destroy();
    }
}
